<template>
  <a-card>
    <div style="margin-bottom: 10px;">
      <a-form layout="inline">
        <a-row :gutter="12">
          <a-col :md="20" :sm="24">
            <a-button style="margin-left: 10px;" type="primary" @click="() => {this.showSetDataList()}">新增</a-button>
            <a-button style="margin-left: 10px;" type="primary" @click="() => { showSpecial = true; specialFlag='1' }">
              特殊单据(增单)
              <span class="tsdj_tip" v-show="selectRowsData.length > 0">{{ selectRowsData.length }}</span>
            </a-button>
            <a-button style="margin-left: 10px;" type="primary" @click="() => { showSpecial = true; specialFlag='2' }">
              特殊单据(减单)
              <span class="tsdj_tip" v-show="selectRowsData2.length > 0">{{ selectRowsData2.length }}</span>
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-table border :columns="columns" :dataSource="data" :loading="loading" @change="handleTableChange">
      <span slot="type" slot-scope="text, record">
        <a-tag :color="record.CostTotal ? '#87d068' : '#f50'">
          {{ record.CostTotal ? '已算' : '未算' }}
        </a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleCalc(record)">{{ record.CostTotal ? '重算' : '计算' }}</a>
          <!-- <a @click="handleCalc2(record)">00000</a> -->
        </template>
      </span>
    </a-table>
    <a-modal title="选择计算月份" width="10%" :visible="addModal" @cancel="() => { addModal = false }" @ok="setDataList">
      <div style="display: flex;justify-content: center;align-items: center;">
        <a-month-picker placeholder="选择月份" @change="onChangeMonth" />
      </div>
    </a-modal>
    <a-modal title="计算" :visible="calcModal" :footer="''" :closable="false">
      <div style="display: flex;justify-content: center;align-items: center;flex-direction: column;">
        <a-progress :percent="progressValue" />
        <div>
          <span>{{ calcMsg }}</span>
          <span v-if="calc6Total">({{ calc6Num }}/{{ calc6Total }})</span>
          <span v-if="calc6_1Total">({{ calc6_1Num }}/{{ calc6_1Total }})</span>
          <span v-if="calc4Total">({{ calc4Num }}/{{ calc4Total }})</span>
          <span v-show="calcMsg != '完成！'">...</span>
        </div>
      </div>
      <div v-if="calcResult" style="display: flex;justify-content: center;align-items: center;margin-top: 10px;">
        <a-button
          type="primary"
          @click="() => { calcModal = false, calcResult = false, getDataList(), progressValue = 0 }">确定</a-button>
      </div>
    </a-modal>
    <a-modal :visible="showSpecial" width="80%" @cancel="() => { showSpecial = false }" @ok="selectSpecial">
      <Special ref="special"></Special>
    </a-modal>
  </a-card>
</template>
<script>
import moment from 'moment'
import Special from './special.vue'

const columns = [
  {
    title: '月份',
    dataIndex: 'DateRange'
  },
  {
    title: '状态',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: { Special },
  data () {
    return {
      columns,
      data: [],
      loading: false,
      addModal: false,
      calc6Total: '',
      calc6Num: '',
      calc6_1Total: '',
      calc6_1Num: '',
      calc4Total: '',
      calc4Num: '',
      month: null,
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      calcModal: false,
      calcResult: false,
      calcMsg: '',
      selectRowsData: [],
      selectRowsData2: [],
      showSpecial: false,
      progressValue: 0,
      specialFlag: '1' // 1 增单 2 减单
    }
  },
  watch: {
    showSpecial (val) {
      if (val) {
        this.$refs.special.openForm()
      }
    }
  },
  mounted () {
    this.getDataList()
  },
  methods: {
    selectSpecial () {
      if (this.specialFlag == '1') {
        this.selectRowsData = this.$refs.special.selectRows
      }
      if (this.specialFlag == '2') {
        this.selectRowsData2 = this.$refs.special.selectRows
      }
      this.showSpecial = false
      // this.$refs.special.selectRows = []
    },
    showSetDataList () {
      this.addModal = true
    },
    setDataList () {
      this.addModal = false
      this.$http.post('/BillCode/billcodes_main/SaveData', {
        DateRange: this.month
      }).then(res => {
        this.$message.success('保存成功')
        this.getDataList()
      })
    },
    getDataList () {
      this.$http.post('/BillCode/billcodes_main/GetDataListBySingleCondition', {
      }).then(res => {
        this.data = res.Data || []
      })
    },
    onChangeMonth () {
      this.month = this.timeFormat(arguments[0])
    },
    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM')
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    async handleCalc (record) {
      try {
        this.calcModal = true
        this.calcMsg = '统计发票数据中'
        const progressStpe = Math.ceil(100 / 9)
        await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep1', {
          'ParentId': record.Id,
          'Date': record.DateRange,
          'Ids': this.selectRowsData || [],
          'Ids1': this.selectRowsData2 || []
        })
        this.progressValue = progressStpe * 1
        this.calcMsg = '统计红字发票中'
        await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep2', {
          'ParentId': record.Id,
          'Date': record.DateRange,
          'Ids': this.selectRowsData
        })
        this.progressValue = progressStpe * 2
        this.calcMsg = '统计已出库但未开票的数据中'
        // await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep3', {
        //     "ParentId": record.Id,
        //     "Date": record.DateRange,
        //     "Ids": this.selectRowsData
        // })

        const result0 = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep0', {
          'ParentId': record.Id,
          'Date': record.DateRange,
          Id: '0'
        })
        let EachId0 = null
        const step0 = Math.ceil(result0.Data.Total / 100) - 1
        for (let i = 0; i < step0; i++) {
          const res = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep0', {
            'ParentId': record.Id,
            'Date': record.DateRange,
            Id: i == 0 ? result0.Data.Id : EachId0
          })
          EachId0 = res.Data.Id
        }

        const result0_1 = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep0_1', {
          'ParentId': record.Id,
          'Date': record.DateRange,
          Id: '0'
        })
        let EachId0_1 = null
        const step0_1 = Math.ceil(result0_1.Data.Total / 100) - 1
        for (let i = 0; i < step0_1; i++) {
          const res = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep0_1', {
            'ParentId': record.Id,
            'Date': record.DateRange,
            Id: i == 0 ? result0_1.Data.Id : EachId0_1
          })
          EachId0_1 = res.Data.Id
        }

        this.progressValue = progressStpe * 3
        this.calcMsg = '统计业务仓库数据中'
        const result = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep4', {
          'ParentId': record.Id,
          Id: '0'
        })
        this.calc4Total = result.Data.Total
        this.calc4Num = 500
        const step = Math.ceil(result.Data.Total / 500) - 1
        let EachId = null
        for (let i = 0; i < step; i++) {
          this.calc4Num = 500 * (i + 1)
          const res = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep4', {
            'ParentId': record.Id,
            Id: i == 0 ? result.Data.Id : EachId
          })
          EachId = res.Data.Id
        }
        this.progressValue = progressStpe * 4
        this.calc4Total = ''
        this.calcMsg = '统计财务仓库数据中'
        await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep5', {
          'ParentId': record.Id
        })
        this.progressValue = progressStpe * 5
        this.calcMsg = '计算成本数据中'

        await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GetCostPrice', {
          'StartTime': record.DateRange,
          'EndTime': record.DateRange
        })
        this.progressValue = progressStpe * 6
        this.calcMsg = '统计成本数据中'

        const result6 = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep6', {
          'ParentId': record.Id,
          'Date': record.DateRange,
          Id: '0'
        })
        this.calc6Total = result6.Data.Total
        this.calc6Num = 100
        const step6 = Math.ceil(result6.Data.Total / 100) - 1
        let EachId6 = null
        for (let i = 0; i < step6; i++) {
          this.calc6Num = 100 * (i + 1)
          const res = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep6', {
            'ParentId': record.Id,
            'Date': record.DateRange,
            Id: i == 0 ? result6.Data.Id : EachId6
          })
          EachId6 = res.Data.Id
        }
        this.calc6Total = ''
        this.progressValue = progressStpe * 7
        this.calcMsg = '计算退货成本中'

        // let result6_1 = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep6_1', {
        //     "ParentId": record.Id,
        //     "Date": record.DateRange,
        //     "Id": 0
        // })
        // if (!result6_1.Success){
        //     this.calcMsg = '计算上月成本数据中';

        //     await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep6_1', {
        //         "StartTime": result6_1.Data,
        //         "EndTime": result6_1.Data
        //     })
        //     result6_1 = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep6_1', {
        //         "ParentId": record.Id,
        //         "Date": record.DateRange,
        //         "Id": 0
        //     })
        // }
        // this.calc6_1Total = result6_1.Data.Total;
        // this.calc6_1Num = 100;
        // let step6_1 = Math.ceil(result6_1.Data.Total / 100) - 1;
        // let EachId6_1 = null;
        // for (let i = 0; i < step6_1; i++) {
        //     this.calc6_1Num = 100 * (i + 1);
        //     let res = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep6_1', {
        //         "ParentId": record.Id,
        //         "Date": record.DateRange,
        //         Id: i == 0 ? result6_1.Data.Id : EachId6_1,
        //     })
        //     EachId6_1 = res.Data.Id;
        // }

        const result6_1 = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep6_1', {
          'ParentId': record.Id,
          'Date': record.DateRange,
          Id: '0'
        })
        let EachId6_1 = null
        const step6_1 = Math.ceil(result6_1.Data.Total / 100) - 1
        for (let i = 0; i < step6_1; i++) {
          const res = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep6_1', {
            'ParentId': record.Id,
            'Date': record.DateRange,
            Id: i == 0 ? result6_1.Data.Id : EachId6_1
          })
          EachId6_1 = res.Data.Id
        }

        this.calc6_1Total = ''
        this.progressValue = progressStpe * 8
        this.calcMsg = '计算数据合计中'
        await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep7', {
          'ParentId': record.Id,
          'Date': record.DateRange,
          'Ids': this.selectRowsData
        })
        this.progressValue = 100
        this.calcMsg = '完成！'
        this.calcResult = true
      } catch {
        this.$message.error('计算失败，请重新尝试!')
      }
    },
    async handleCalc2 (record) {
      const result0 = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep0', {
        'ParentId': record.Id,
        'Date': record.DateRange,
        Id: '0'
      })
      let EachId0 = null
      const step0 = Math.ceil(result0.Data.Total / 100) - 1
      for (let i = 0; i < step0; i++) {
        const res = await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep0', {
          'ParentId': record.Id,
          'Date': record.DateRange,
          Id: i == 0 ? result0.Data.Id : EachId0
        })
        EachId0 = res.Data.Id
      }
    }
  }
}
</script>
<style lang="less" scoped>
	.tsdj_tip{
		padding:0 5px;
		background: red;
		margin-left: 3px;
		font-size: 10px;
		border-radius: 20px;
	}
</style>
